package com.aimusic.filter;

import com.aimusic.utils.CurrentHolder;
import com.aimusic.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {

    private final JwtUtils jwtUtils;

    @Autowired
    public TokenFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        // 1. 登录/注册等公开接口直接放行（原有逻辑保留）
        if (requestURI.contains("/login") || requestURI.contains("/send-sms")
                || requestURI.contains("/register") || requestURI.contains("/send-forgot-sms")
                || requestURI.contains("/forgot-password")) {
            log.info("登录/注册请求，路径: {}, 放行", requestURI);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 2. 关键修改：优先从URL参数提取Token（适配WebSocket），再从Header提取（适配普通HTTP）
        log.info("请求: {}，获取token", requestURI);
        String token = request.getParameter("token"); // 第一步：从URL参数拿Token（WebSocket用）
        if (token == null || token.trim().isEmpty()) { // 如果URL没有，再从Header拿（普通HTTP用）
            token = request.getHeader("Authorization");
            // （可选）如果Header是Bearer Token格式（比如 "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."），需要去掉前缀
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7); // 截取"Bearer "后面的真实Token
            }
        }

        // 3. Token仍为空，返回401（原有逻辑保留）
        if (token == null || token.trim().isEmpty()) {
            log.warn("请求: {} 未携带token，响应401", requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        // 4. 校验Token（原有逻辑不变）
        try {
            Claims claims = jwtUtils.parseJWT(token);
            Integer userId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(userId);
            log.info("请求: {} 的token校验通过，当前用户ID: {}", requestURI, userId);
        } catch (Exception e) {
            log.warn("请求: {} 的token非法或已过期，错误: {}", requestURI, e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        // 5. 放行并清理ThreadLocal（原有逻辑不变）
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            CurrentHolder.remove(); // 确保ThreadLocal无论如何都被清理，防止内存泄漏
        }
    }
}